package com.hctforgreen.greenservice.ctr;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;

import com.hctforgreen.greenservice.db.DbFeedBackAdapter;
import com.hctforgreen.greenservice.model.FeedBackListEntity;
import com.hctforgreen.greenservice.model.FeedBackListEntity.FeedBackEntity;
import com.hctforgreen.greenservice.service.HctApplication;
import com.hctforgreen.greenservice.utils.HctConstants;

/**
 * db的控制器
 * 
 * @author Tallen Zhai
 * 
 */
public class DbFeedBackController {

	private DbFeedBackAdapter mDbAdapter;

	public DbFeedBackController(Context context) {
		mDbAdapter = ((HctApplication) context.getApplicationContext())
				.getDbFeedBackAdapter();
	}

	// ============================
	// delete
	// ============================
	public boolean delete(FeedBackEntity entity) {
		if (entity._id == 0) {
			entity._id = get_idFromDb(entity);
		}
		if (entity._id != -1) {
			String sql = "delete from " + HctConstants.DB_TABLE_NAME_FEED_BACK_LST
					+ " where _id=?";
			mDbAdapter.execSQL(sql, new Object[] { entity._id });
			return true;
		}
		return false;
	}

	// ============================
	// Entity insertOrUpdate
	// ============================
	public boolean insertOrUpdate(FeedBackEntity entity) {
		if (isExists(entity)) {
			update(entity);
		} else {
			insert(entity);
		}
		return true;
	}

	// ============================
	// Entity update
	// ============================
	private void update(FeedBackEntity entity) {
		StringBuffer sb = new StringBuffer();
		for (String sPicName : entity.picNames) {
			sb.append(sPicName);
			if (!entity.picNames.get(
					entity.picNames.size() - 1).equals(sPicName)) {
				sb.append(",");
			}

		}
		String sql = "update " + HctConstants.DB_TABLE_NAME_FEED_BACK_LST
				+ " set content='" + entity.content + "'"
				+ ",answerContent='" + entity.answerContent + "'" 
				+ ",title='" + entity.title + "'" 
				+ ",answerName='" + entity.answerName + "'" 
				+ ",seriesName='" + entity.seriesName + "'" 
				+ ",submitDate='" + entity.submitDate + "'" 
				+ ",picNames='" + sb.toString() + "'" 
				+ " where id='" + entity.id
				+ "'";

		mDbAdapter.execSQL(sql);
	}
	
	private void deleteDeprecatedFeedBackListEntity(FeedBackListEntity listEntity) {
		FeedBackListEntity inDbListEntity = getFeedBackListEntity();
		List<FeedBackEntity> deprecatedList = new ArrayList<FeedBackEntity>();
		if (inDbListEntity.dataList == null) {
			return;
		}
		for (FeedBackEntity inDbEntity : inDbListEntity.dataList) {
			boolean bDeprecated = true;
			for (FeedBackEntity inNetEntity : listEntity.dataList) {
				if (inDbEntity.id.equals(inNetEntity.id)) {
					bDeprecated = false;
				}
			}
			if (bDeprecated) {
				deprecatedList.add(inDbEntity);
			}

		}
		for (FeedBackEntity entity : deprecatedList) {
			delete(entity);
		}
	}

	// ============================
	// ListEntity insert
	// ============================
	/**
	 * 插入FeedBackJsonByPersonIdListEntity
	 * 
	 * @param entities
	 * @return
	 */
	public boolean insert(FeedBackListEntity listEntity) {
		boolean bState = false;
		mDbAdapter.beginTransaction();
		try {
			deleteDeprecatedFeedBackListEntity(listEntity);
			for (FeedBackEntity entity : listEntity.dataList) {
				if (insertOrUpdate(entity)) {
					bState = true;
				}
			}
			
			mDbAdapter.setTransactionSuccessful();
		} finally {
			mDbAdapter.endTransaction();
		}
		
		return bState;
	}

	// ============================
	// Entity insert
	// ============================
	public boolean insert(FeedBackEntity entity) {
		if (isExists(entity)) {
			return false;
		} else {
			StringBuffer sb = new StringBuffer();
			for (String sPicName : entity.picNames) {
				sb.append(sPicName);
				if (!entity.picNames.get(
						entity.picNames.size() - 1).equals(sPicName)) {
					sb.append(",");
				}

			}
			String sql = "insert into " + HctConstants.DB_TABLE_NAME_FEED_BACK_LST
					+ " (id,"
					+ "content,"
					+ "answerContent,"
					+ "title,"
					+ "answerName,"
					+ "seriesName,"
					+ "submitDate,"
					+ "picNames)" + " values " + "(?,?,?,?,?,?,?,?);";
			mDbAdapter.execSQL(sql, new Object[] { 
					entity.id,
					entity.content,
					entity.answerContent,
					entity.title,
					entity.answerName,
					entity.seriesName,
					entity.submitDate,
					sb.toString() });
			return true;
		}
	}

	// ============================
	// Entity isExists
	// ============================
	/**
	 * 判断此条FeedBackJsonByPersonIdEntity在db中是否已经存在
	 * 
	 * @param entity
	 * @return
	 */
	public boolean isExists(FeedBackEntity entity) {
		String sql = "select count(*) from "
				+ HctConstants.DB_TABLE_NAME_FEED_BACK_LST + " where id='"
				+ entity.id + "'";
		Cursor cursor = mDbAdapter.rawQuery(sql, null);
		cursor.moveToFirst();
		if (cursor.getInt(0) > 0) {
			cursor.close();
			return true;
		} else {
			cursor.close();
			return false;
		}
	}

	// ============================
	// Entity Lst
	// ============================

	public FeedBackListEntity getFeedBackListEntity(){
		FeedBackListEntity listEntity = new FeedBackListEntity();
		listEntity.dataList = getFeedBackEntityLst();
		return listEntity;
	}
	
	public ArrayList<FeedBackEntity> getFeedBackEntityLst() {

		Cursor cursor = getFeedBackLstCursor();

		ArrayList<FeedBackEntity> list = new ArrayList<FeedBackListEntity.FeedBackEntity>();
		for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
			FeedBackEntity entity = new FeedBackEntity();
			int _idIndex = cursor.getColumnIndex("_id");
			int idIndex = cursor.getColumnIndex("id");
			int contentIndex = cursor.getColumnIndex("content");
			int answerContentIndex = cursor.getColumnIndex("answerContent");
			int titleIndex = cursor.getColumnIndex("title");
			int answerNameIndex = cursor.getColumnIndex("answerName");
			int seriesNameIndex = cursor.getColumnIndex("seriesName");
			int submitDateIndex = cursor.getColumnIndex("submitDate");
			int picNamesIndex = cursor.getColumnIndex("picNames");
			entity._id = cursor.getInt(_idIndex);
			entity.id = cursor.getString(idIndex);
			entity.content = cursor.getString(contentIndex);
			entity.answerContent = cursor.getString(answerContentIndex);
			entity.title = cursor.getString(titleIndex);
			entity.answerName = cursor.getString(answerNameIndex);
			entity.seriesName = cursor.getString(seriesNameIndex);
			entity.submitDate = cursor.getString(submitDateIndex);
			addPicNamesList(cursor, entity, picNamesIndex);
			list.add(entity);
		}
		cursor.close();
		return list;
	}

	private void addPicNamesList(Cursor cursor, FeedBackEntity entity,
			int picNamesIndex) {
		String sPicNameList = cursor
				.getString(picNamesIndex);
		String[] picNameArray = sPicNameList.split(",");
		if (picNameArray != null) {
			for (String sPicName : picNameArray) {
				entity.picNames.add(sPicName);
			}
		}
	}
	// ============================
	// Entity Lst
	// ============================
	
	// ============================
	// Cusrsor
	// ============================

	
	/**
	 * 获取结果游标(Cursor), asc:最早insert的会先被查询到
	 * 
	 * @return
	 */
	private Cursor getFeedBackLstCursor() {

		String sql = "select * from " + HctConstants.DB_TABLE_NAME_FEED_BACK_LST
				+ " order by _id asc";
		Cursor cursor = mDbAdapter.rawQuery(sql, null);
		return cursor;
	}

	// ============================
	// get _id
	// ============================
	private int get_idFromDb(FeedBackEntity entity) {
		String sql = "select _id from " + HctConstants.DB_TABLE_NAME_FEED_BACK_LST
				+ " where " + "id='" + entity.id + "'";
		Cursor cursor = mDbAdapter.rawQuery(sql, null);
		cursor.moveToFirst();
		int _idIndex = cursor.getColumnIndex("_id");
		int _id = -1;
		try {
			_id = cursor.getInt(_idIndex);
			cursor.close();
		} catch (Exception e) {
			cursor.close();
		}
		return _id;
	}

}
